package com.zhangzhan.gulimallcommcon.validator.validinterface.product.constraint;

import com.zhangzhan.gulimallcommcon.validator.validinterface.product.myinterface.BrandShowStatusValid;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.HashSet;
import java.util.Set;


/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/6/15 22:22
 */
public class BrandShowStatusValidConstraint implements ConstraintValidator<BrandShowStatusValid, Integer> {

    Set<Integer> set = new HashSet<>();

    /**
     * Initializes the validator in preparation for
     * {@link #isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     *                             初始化方法
     */
    @Override
    public void initialize(BrandShowStatusValid constraintAnnotation) {
        int[] value = constraintAnnotation.value();
        for (int val : value) {
            set.add(val);
        }
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value==null){
            return false;
        }
        return set.contains(value);
    }
}
